Ga naar hoofdinhoud

strategy

export const items = [
{ name: "Laptop", price: 1200 },
{ name: "Smartphone", price: 800 },
{ name: "Tablet", price: 600 },
{ name: "Monitor", price: 300 },
];


// strategies/SortStrategies.js
export const SortByName = (a, b) => {
return a.name.localeCompare(b.name);
};

export const SortByPriceAscending = (a, b) => {
return a.price - b.price;
};

export const SortByPriceDescending = (a, b) => {
return b.price - a.price;
};

// strategies/FilterStrategies.js
export const FilterByPriceAbove = (minPrice) => (item) => {
return item.price > minPrice;
};

// Vue applicatie
<template>
<div>
<div>
<button @click="setSortStrategy(SortByName)">Sorteer op Naam</button>
<button @click="setSortStrategy(SortByPriceAscending)">Sorteer op Prijs (Laag naar Hoog)</button>
<button @click="setSortStrategy(SortByPriceDescending)">Sorteer op Prijs (Hoog naar Laag)</button>
<button @click="setFilterStrategy(FilterByPriceAbove(500))">Filter: Prijs > 500</button>
</div>

<ul>
<li v-for="item in sortedAndFilteredItems" :key="item.name">
{{ item.name }} -{{ item.price }}
</li>
</ul>
</div>
</template>

<script>
import { ref, computed } from "vue"; // Import Composition API functies
import { items } from "@/data/items"; // De onveranderde lijst
import { SortByName, SortByPriceAscending, SortByPriceDescending } from "@/strategies/SortStrategies";
import { FilterByPriceAbove } from "@/strategies/FilterStrategies";

export default {
setup() {
// Data met ref
const itemList = ref(items); // De oorspronkelijke lijst
const sortStrategy = ref(SortByName); // Standaard sorteermethode
const filterStrategy = ref(null); // Geen filter standaard

// Computed property voor gesorteerde en gefilterde items
const sortedAndFilteredItems = computed(() => {
let filteredItems = filterStrategy.value
? itemList.value.filter(filterStrategy.value)
: itemList.value;
return [...filteredItems].sort(sortStrategy.value);
});

// Methodes om strategieën aan te passen
const setSortStrategy = (strategy) => {
sortStrategy.value = strategy;
};

const setFilterStrategy = (strategy) => {
filterStrategy.value = strategy;
};

return {
sortedAndFilteredItems, // Computed property om te gebruiken in de template
setSortStrategy, // Methode om de sorteermethode in te stellen
setFilterStrategy, // Methode om de filterstrategie in te stellen
};
},
};
</script>

<style scoped>
/* Stijlen kunnen hetzelfde blijven als voorheen */
</style>